package com.kfgj.hkp.manager;

import com.kfgj.hkp.common.BaseEntity;
import com.kfgj.hkp.common.context.CurrentContext;
import com.kfgj.hkp.common.dataaccess.PageResult;
import com.kfgj.hkp.common.dataaccess.mybatis.IMyBatisBaseDao;
import com.kfgj.hkp.common.exception.RestBusinessException;
import com.kfgj.hkp.common.utils.OperateFillUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by liwensihan on 2018/5/23.
 */
public abstract class AbstractManager<T extends BaseEntity> implements IManager<T> {


    protected abstract IMyBatisBaseDao<T, Long> getMyBatisDao();


    @Override
    public T findOne(String prop, Object value) {
        return this.getMyBatisDao().selectUniqueByProp(prop, value);
    }

    @Override
    public T findOne(Map<String, Object> param) {
        return this.getMyBatisDao().selectUniqueByMap(param);
    }

    @Override
    public List<T> findByMap(Map<String, Object> param) {

        return this.getMyBatisDao().selectByMap(param);
    }

    @Override
    public List<T> findByMap(Map<String, Object> param, String orderBy, boolean isAsc) {
        return this.getMyBatisDao().selectByMap(param, orderBy, isAsc);
    }

    @Override
    public PageResult<T> findByMap(Map<String, Object> param, int start, int pageSize) {

        return this.getMyBatisDao().selectByMap(param, start, pageSize);
    }

    @Override
    public PageResult<T> findByMap(Map<String, Object> param, int start, int pageSize, String orderBy, boolean isAsc) {
        return this.getMyBatisDao().selectByMap(param, start, pageSize, orderBy, isAsc);
    }

    @Transactional
    @Override
    public int create(T t) {
        OperateFillUtils.fill(t);

        beforeCreate(t);

        int rs = getMyBatisDao().insert(t);

        afterCreate(t);

        return rs;


    }


    /**
     * 扩展在新增数据之前可以做的事情
     *
     * @param t
     */
    protected void beforeCreate(T t) {

    }


    protected void afterCreate(T t) {

    }

    @Transactional
    @Override
    public int update(T t) {

        if (StringUtils.isNotEmpty(CurrentContext.getUserCode())) {
            t.setLastUpdateCode(CurrentContext.getUserCode());
            if (null != CurrentContext.getUserInfo()) {
                t.setLastUpdateName(CurrentContext.getUserInfo().getUserName());
            }
        }


        t.setLastUpdateTime(new Date());

        beforeUpdate(t);

        int rs = this.getMyBatisDao().update(t);

        afterUpdate(t);

        return rs;
    }

    protected void beforeUpdate(T t) {

        if (t.getId() == null) {
            throw new RestBusinessException("更新数据，ID不能为空");
        }

    }

    protected void afterUpdate(T t) {

    }
}
